const blurHandler = function (e: Event | { target: HTMLInputElement }) {
  const el = e.target as HTMLInputElement
  let tempEl = el.parentElement
  while (tempEl) {
    const classList = [...tempEl.classList]
    if (classList.includes('sg-form-item')) {
      tempEl.classList.remove('sg-focus-within')
      if (el.value) {
        tempEl.classList.add('sg-input-value')
      } else {
        tempEl.classList.remove('sg-input-value')
      }
      el.removeEventListener('blur', blurHandler)
      break
    }
    tempEl = tempEl.parentElement
  }
}

const focusHandler = function (e: Event) {
  const el = e.target as HTMLInputElement
  let tempEl = el.parentElement
  while (tempEl) {
    const classList = [...tempEl.classList]
    if (classList.includes('sg-form-item')) {
      tempEl.classList.add('sg-focus-within')
      el.addEventListener('blur', blurHandler)
      break
    }
    tempEl = tempEl.parentElement
  }
}

export default function (app: any) {
  app.directive('focus-within', {
    created: function () {},
    beforeMount: function (el: HTMLInputElement) {
      el.addEventListener('focus', focusHandler)
    },
    mounted: function (el: HTMLInputElement) {
      blurHandler({ target: el })
    },
    updated: function () {},
    unmounted: function (el: HTMLInputElement) {
      el.removeEventListener('focus', focusHandler)
    }
  })
}
